package bavaria.hightech.banking.logging;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.logging.Logger;

import bavaria.hightech.banking.bank.BankImpl;

public class LoggingInvocationHandler implements InvocationHandler {

	private static Logger logger = Logger
			.getLogger(LoggingInvocationHandler.class.getName());

	private final BankImpl bank;

	public LoggingInvocationHandler(BankImpl bank) {
		super();
		this.bank = bank;
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		String argsString = getArgsString(args);
		Object returnvalue;
		try {
			returnvalue = method.invoke(bank, args);
		} catch (Exception e) {
			logger.fine("Call to " + bank.getClass().getSimpleName() + "."
					+ method.getName() + argsString + " Exception: "
					+ e.toString());
			throw e.getCause();
		}
		logger.fine("Call to " + bank.getClass().getSimpleName() + "."
				+ method.getName() + argsString + " returns: " + returnvalue);
		return returnvalue;
	}

	private String getArgsString(Object[] args) {
		StringBuilder arguments = new StringBuilder();
		arguments.append("(");
		for (int i = 0; i < args.length; i++) {
			arguments.append(args[i].toString());
			if (i < args.length - 1) {
				arguments.append(", ");
			}
		}
		arguments.append(")");
		return arguments.toString();
	}
}
